const {
  $util,
} = getApp();
Page({
  data: {
    page: 1,
    list: [],
    hasMore: true,
    nav: [{ id: 0, title: '待考试' }, { id: 1, title: '已考试' }],
    testId: 0,
    imgUrl: $util.getImgUrl(),
  },
  onLoad(opts) {
    this.loadList();
    wx.setNavigationBarTitle({
      title: opts.barTitle && decodeURIComponent(opts.barTitle) || '考试中心',
    });
  },
  changeNav(e) {
    let { id } = e.detail.obj;
    this.setData({
      page: 1,
      testId: id,
      list: [],
      loaded: false,
    }, () => {
      this.loadList();
    });
  },
  loadList() {
    const D = this.data;
    $util.request({
      url: D.testId === 0 ? 'entry/wxapp/edu.exam.exammain' : 'entry/wxapp/edu.exam.examrecordmain',
      data: {
        page: D.page,
      },
      success: (res) => {
        let list = res.data;
        if (D.page > 1) {
          list = [...D.list, ...list];
        }
        this.setData({
          list,
          hasMore: parseInt(res.total, 0) > list.length,
          loaded: true,
        });
      },
    });
  },
  onReachBottom() {
    if (!this.data.hasMore) return;
    this.setData({
      page: this.data.page + 1,
    }, () => {
      this.loadList();
    });
  },
  // 跳转至试卷详情
  toDetail(e) {
    const idx = e.currentTarget.dataset.idx;
    const D = this.data;
    const item = D.list[idx];
    const url = `/ws_party_const/pages/education/train/network/test/detail?id=${item.id}&barTitle=${item.title}`;
    if (Number(item.isstart) === 1) {
      wx.navigateTo({
        url,
      });
    } else {
      wx.showToast({
        title: '考试还未开始',
        duration: 1e3,
        icon: 'none',
      });
    }
  },
});
